package com.lsj.ssmTest.core.interceptor;

import com.lsj.ssmTest.model.User;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Lsj
 * @version 1.0
 * @date 2021/6/29 8:46
 */
public class AutoInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 获取请求需要执行的方法名
        String methodName = handlerMethod.getMethod().getName();
        // 判断当前请求是否和登录操作相关
        HttpSession session = request.getSession(true);
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            response.sendRedirect(request.getContextPath() + "/");
            // 终止后续请求
            return false;
        }
        // 放行
        return super.preHandle(request, response, handler);
    }
}
